package com.fatdetection.demo.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fatdetection.demo.bean.User;
import com.fatdetection.demo.bean.UserExcel;
import com.fatdetection.demo.mapper.UserMapper;
import com.fatdetection.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImp implements UserService{

    @Autowired
    UserMapper userMapper;

    @Override
    public User login(String phone, String password) {
        return userMapper.selectOne(new QueryWrapper<User>()
        .eq("phone", phone)
        .eq("password", DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8))));
    }

    @Override
    public Map<String, Object> insertList(List<Object> datalist, String filename) {
        List<User> allData = findAll();
        Map<String, Object> rstMap = new HashMap<>();
        List<UserExcel> errorItemObj = new ArrayList<>();
        int errorItem = 0;
        int successItem = 0;
        Map<String, String> checkLists = new HashMap<>();
        for (User allDatum : allData) {
            String studentId = allDatum.getStudentId();
            String schoolName = allDatum.getSchoolName();
            checkLists.put(studentId, schoolName);
        }
        for (Object userExcel : datalist) {
            User user = toUser(userExcel);
            if(checkLists.containsKey(user.getStudentId())) {
                if(user.getSchoolName().equals(checkLists.get(user.getStudentId()))){
                    // 数据重复，跳过写入，
                    errorItem++;
                    errorItemObj.add((UserExcel) userExcel);
                } else {
                    // id相同但是学校不同
                    userMapper.insert(user);
                    successItem++;
                }
            } else{
                userMapper.insert(user);
                successItem++;
            }
        }
        rstMap.put("filename", filename);
        rstMap.put("successNum", successItem);
        rstMap.put("errorNum", errorItem);
        rstMap.put("errorItem", errorItemObj);
        return rstMap;
    }

    @Override
    public Page<User> selectAllPage(Integer current, Integer size, String searchKey, String searchVal) {
        QueryWrapper<User> query = new QueryWrapper<User>().like(searchKey, searchVal);
        Page<User> page = new Page<>(current, size);
        if(searchKey == null || searchVal == null){
            query = null;
        }
        return userMapper.selectPage(page, query);
    }

    @Override
    public int insertUser(User user) {
        if(user.getPassword() != null){
            user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        }
        if(findUserByPhone(user.getPhone()) == null){
            return userMapper.insert(user);
        } else{
            return -2; //手机号重复
        }
    }

    @Override
    public Boolean delUser(String phone) {
        return userMapper.delete(
                new QueryWrapper<User>()
                .eq("phone", phone)
        ) == 1;
    }

    @Override
    public Boolean updateUser(User user) {
        if(user.getPassword() != null){
            // 用户修改密码
            String md5pwd = DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8));
            user.setPassword(md5pwd);
        }
        return userMapper.update(user, new UpdateWrapper<User>()
                .eq("phone",user.getPhone())
        ) == 1;
    }

    @Override
    public List<User> findAll() {
        return userMapper.selectList(null);
    }

    @Override
    public List<User> findUserByGroup(int groupId) {
        return userMapper.selectList(new QueryWrapper<User>()
        .eq("group_id", groupId));
    }

    @Override
    public List<User> findUserByGroupAndOrder(int groupId) {
        return userMapper.selectList(new QueryWrapper<User>()
                .eq("group_id", groupId)
                .gt("order_no", 0));
    }

    @Override
    public User findUserByIdAndSchool(String studentId, String schoolName) {
        return userMapper.selectOne(new QueryWrapper<User>()
                .eq("school_name", schoolName)
                .eq("student_id", studentId));
    }

    @Override
    public List<User> searchUser(String info, Integer projectId) {
        try {
            URLDecoder.decode(info,"utf-8");
            return userMapper.selectList(new QueryWrapper<User>()
                    .eq("project_id", projectId).and(query -> {
                        query.like("phone", info);
                    }));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public List<User> searchUserByPhoneAndName(String info, Integer projectId) {
        try {
            URLDecoder.decode(info,"utf-8");
            return userMapper.selectList(new QueryWrapper<User>()
                    .eq("project_id", projectId).and(query -> {
                        query.like("phone", info).or().like("username", info);
                    }));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public List<User> findUserByProj(String projectName) {
        return userMapper.findUserByProj(projectName);
    }

    @Override
    public User findUserByPhone(String phone) {
        return userMapper.selectOne(new QueryWrapper<User>()
                .eq("phone", phone));
    }

    @Override
    public List<User> findUsersByProjectId(Integer projectId) {
        return userMapper.selectList(new QueryWrapper<User>()
                .eq("project_id", projectId));
    }

    public User toUser(Object object){
        UserExcel data = (UserExcel) object;
        User user = new User();
        user.setPassword(data.getPassword());
        user.setStudentId(data.getStudent_id());
        user.setUsername(data.getUsername());
        user.setBirthday(data.getBirthday());
        user.setEmail(data.getEmail());
        user.setGender(data.getGender());
        user.setGroupId(data.getGroup_id());
        user.setBirthday(data.getBirthday());
        user.setCreateTime(data.getCreate_time());
        user.setLastTime(data.getLast_time());
        user.setOrderNo(data.getOrder_no());
        user.setPhone(data.getPhone());
        user.setSchoolName(data.getSchool_name());
        user.setProjectId(data.getProject_id());
        user.setWechatId(data.getWechatId());
        user.setQq(data.getQq());
        return user;
    }


}
